<template>
    <div class="bac_color_box">
        <div class="main_content">
            <div class="left_img_area">
                <div class="logo_show">
                    <i class="logo"></i>
                    光谷
                </div>
                <div class="system_name">
                    智慧交通系统管理平台
                </div>
                <img class="smart_traffic_img" src="@/imgs/智慧交通.png" alt="">
            </div>

            <div class="right_login_area">
                <div class="choose_identify">请选择您的身份：</div>
                <div class="users_list">
                    <div @click="() => { $store.changeUserType('common') }"
                        :class="['common_user', { 'blue_bac_color': $store.userType == 'common' ? true : false }]">
                        <img src="@/imgs/用户.png" alt="" class="hover_scale">
                        <span>普通用户</span>
                    </div>
                    <div @click="() => { $store.changeUserType('traffic') }"
                        :class="['traffic_police', { 'blue_bac_color': $store.userType == 'traffic' ? true : false }]">
                        <img src="@/imgs/交警.png" alt="" class="hover_scale">
                        <span>交通部门</span>
                    </div>
                    <div @click="() => { $store.changeUserType('admin') }"
                        :class="['administer', { 'blue_bac_color': $store.userType == 'admin' ? true : false }]">
                        <img src="@/imgs/管理员.png" alt="" class="hover_scale">
                        <span>超级管理员</span>
                    </div>
                </div>

                <div class="welcome_by_time">
                    {{ timeInfor }}好！欢迎用户使用
                </div>
                <div class="login_unique_module" v-if="toggleLogin">
                    <div class="login_operation" ref="localUsersInput">
                        <div class="user_name" @click='() => { if (localUsers.length >= 1) { isLocalUsers = true } }'>
                            <input type="text" v-model="userName" placeholder="请输入用户名"
                                @input='() => { isLocalUsers = false }'>
                        </div>
                        <div :class="['local_user_infor', { 'open_drap_down_box': isLocalUsers }]">

                            <div class="local_user_infor_list" v-for="item in localUsers"
                                @click="loginByLocalUser(item)">
                                本地用户：&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                {{ item.username }}
                            </div>
                        </div>

                        <div class="user_password" ref="passwordInput">
                            <input type="password" v-model="password" @input="changePassword" placeholder="请输入密码">
                            <div class="password_tip" v-if="isPasswordTip">请输入长度为6到11位包含英文(大写或小写)或数字字符的密码</div>
                        </div>
                    </div>

                    <div :class="['remember_user', { 'blue_font_color': isRemember }]">
                        <input type="checkbox" v-model="isRemember">记住我
                    </div>

                    <div class="login_btn" @click="loginAccount">
                        登录
                    </div>

                    <div class="register_user" v-show="$store.userType == 'common'">
                        如您还没有账号？
                        <span class="go_register_btn" @click="() => { toggleLogin = false }">注册账号</span>
                    </div>
                </div>


                <div class="register_unique_module" v-else>
                    <div class="login_operation">
                        <div class="user_name">
                            <input type="text" v-model="userName" placeholder="请输入用户名">
                        </div>

                        <div class="user_password" ref="passwordInput">
                            <input type="password" v-model="password" @input="changePassword" placeholder="请输入密码">
                            <div class="password_tip" v-if="isPasswordTip">请输入长度为6到11位包含英文(大写或小写)或数字字符的密码</div>
                        </div>

                        <div class="user_password" ref="secondPasswordInput">
                            <input type="password" v-model="secondPassword" @input="changePasswordAgain"
                                placeholder="请再次输入密码">
                            <div class="password_tip" v-if="isPasswordSameTip">两次密码不一致</div>
                        </div>
                    </div>
                    <div class="login_btn register_btn " @click="registerAccount">
                        注册
                    </div>
                    <div class="loginBack" @click="() => { toggleLogin = true }">
                        < 返回登录 </div>

                    </div>
                </div>

                <div class="login_fail_tip fail_tip" v-if="isLoginFailRes">
                    用户名或密码错误
                </div>

                <div class="register_res_tip" v-if="isRegisterRes">
                    <div class="register_success  success_tip" v-if="isRegisterSuccess">注册成功</div>
                    <div class="register_fail fail_tip" v-else>{{ registerFailReason }}</div>
                </div>

            </div>

        </div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { useLoginStore } from '@/stores/counter.js'
import { useRouter } from 'vue-router'
let $router = useRouter()
let $store = useLoginStore()
// 时间信息，其值有上午||中午||下午||晚上
let timeInfor = ref('')
// 用户名
let userName = ref(null)
// 密码
let password = ref(null)
// 是否记住账号
let isRemember = ref(false)
// 密码输入框DOC对象
let passwordInput = ref(null)
// 是否展示密码提示
let isPasswordTip = ref(false)
// 是否展示登录错误结果
let isLoginFailRes = ref(false)
// 是否展示注册结果
let isRegisterRes = ref(false)
// 注册是否成功
let isRegisterSuccess = ref(false)
// 注册失败原因
let registerFailReason = ref(false)
// 切换登录/注册
let toggleLogin = ref(true)
// 第二次输入的密码
let secondPassword = ref()
// 第二次密码输入框DOC对象
let secondPasswordInput = ref(null)
// 判断注册时两次密码是否相同
let isPasswordSameTip = ref(false)
// 存贮的本地用户
let localUsers = ref([])
// 本地用户下拉框
let localUsersInput = ref(null)
// 是否展开本地用户
let isLocalUsers = ref(false)



onMounted(() => {
    // 时间信息赋值
    timeInfor.value = getTimeInfor()
    // 获取本地存储的用户
    JSON.parse(localStorage.getItem('localUsers')) ?
        localUsers.value = JSON.parse(localStorage.getItem('localUsers')) :
        []
})
// 获取时间信息
function getTimeInfor() {
    let res
    const nowTime = new Date()
    const nowhours = nowTime.getHours()

    if (nowhours >= 6 && nowhours < 12) {
        res = "上午"
    } else if (nowhours == 12) {
        res = "中午"
    }
    else if (nowhours >= 13 && nowhours < 18) {
        res = "下午"
    } else {
        res = "晚上"
    }
    return res
}
// 判断输入的密码是否符合规范
function changePassword() {
    // 密码规范：6-11位数字或英文字符
    if (/^[A-Za-z0-9]{6,11}$/.test(password.value)) {
        passwordInput.value.style.borderColor = ' #cdcdcd'
        isPasswordTip.value = false
    } else {
        passwordInput.value.style.borderColor = 'red'
        isPasswordTip.value = true
    }
}
// 登录账户
async function loginAccount() {
    const res = await axios.post('http://localhost:3000/api/login', { "username": userName.value, "password": password.value, "type": $store.userType })
    console.log(res)
    // code==400，登录失败;code==200,登录成功
    if (res.code == 400) {
        isLoginFailRes.value = true
        setTimeout(() => {
            isLoginFailRes.value = false
        }, 1000)
    } else {
        localStorage.setItem('token', res.token)
        $router.push('/map')
        let userObject={
            "username": userName.value,
            "type": $store.userType,
            "password": password.value
        }
        //存储当前登录用户信息
        $store.setCurrentUser(userObject)
        // 登录成功前往项目首页
        
    }
    // 勾选了‘记住我’且登录成功，则在本地储存该用户信息
    if (res.code == 200 && isRemember.value == true) {

        localUsers.value.push({
            "username": userName.value,
            "type": $store.userType,
            "password": password.value
        })
        localStorage.setItem('localUsers', JSON.stringify(localUsers.value))
    }
}
// 通过本地账户登录
function loginByLocalUser(userInfor) {
    userName.value = userInfor.username
    $store.changeUserType(userInfor.type)
    password.value = userInfor.password
    isLocalUsers.value = false
}
// 当点击除本地用户下拉框以外的任一元素时，下拉框消失
document.addEventListener("click", (evt) => {
    if (localUsersInput.value && !localUsersInput.value.contains(evt.target)) {
        isLocalUsers.value = false
    }
})
// 判断注册用户时，两次输入的密码是否相同
function changePasswordAgain() {
    if (secondPassword.value == password.value) {
        secondPasswordInput.value.style.borderColor = '#cdcdcd'
        isPasswordSameTip.value = false
    } else {
        secondPasswordInput.value.style.borderColor = 'red'
        isPasswordSameTip.value = true
    }
}
//  注册用户
async function registerAccount() {
    // 若两次输入密码一致则发送post请求
    if (isPasswordSameTip.value == false) {
        const res = await axios.post('/api/register', {
            "username": userName.value,
            "type": $store.userType,
            "password": secondPassword.value
        })
        // code==400注册失败
        if (res.code == 400) {
            // 开启注册结果弹窗，显示注册错误原因，1s后弹窗自动关闭
            isRegisterRes.value = true
            isRegisterSuccess.value = false
            registerFailReason.value = res.msg
            setTimeout(() => {
                isRegisterRes.value = false
            }, 1000)

        } else {
            // 注册成功，开启注册结果弹窗，显示注册成功，自动返回登录窗口，1s后弹窗自动关闭
            isRegisterRes.value = true
            isRegisterSuccess.value = true
            setTimeout(() => {
                isRegisterRes.value = false
            }, 1000)
            // 注册成功前往登录
            toggleLogin.value = true
        }
    }
}


</script>
<style scoped lang="scss">
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

.hover_scale:hover {
    transform: scale(1.1);
}

.blue_bac_color {
    background-color: #369bff;
}

.blue_font_color {
    color: #369bff;
}

.open_drap_down_box {
    transform: scaleY(1) !important;
}

.bac_color_box {
    width: 100vw;
    height: 100vh;
    background: rgb(18, 113, 230);
    padding: 20px;

    .main_content {
        display: flex;
        height: 100%;
        padding: 40px 30px;
        background-color: rgb(175, 210, 252);
        border-radius: 30px;

        .left_img_area {
            width: 60%;
            height: 100%;

            .smart_traffic_img {
                margin-top: 40px;
                width: 60%;
                animation: bubble 4s ease-in-out infinite;
            }

            @keyframes bubble {

                0%,
                100% {
                    transform: translateY(0);
                }

                50% {
                    transform: translateY(30px);
                }
            }

            .logo_show {
                font-size: large;
                color: #fff;
            }

            .system_name {
                font-weight: 700;
                font-size: x-large;
                color: #fff;
            }

            .smart_traffic_img {
                margin-left: 15%;
            }
        }

        .right_login_area {
            width: 25%;
            height: 60%;
            margin: 10% 0;
            padding: 30px;
            background-color: #fff;
            margin-left: 10%;
            border-radius: 10px;

            .choose_identify {
                margin-bottom: 20px;
                color: grey;
            }

            .users_list {
                display: flex;
                justify-content: space-around;

                div {
                    width: 4vw;
                    height: 4vw;
                    border-radius: 50%;
                    letter-spacing: 5px;
                    box-shadow: -3px -3px 20px #e4e5e7, 3px 3px 20px #ebebeb;
                    transition: 0.3s;
                    cursor: pointer;

                    img {
                        width: 70%;
                        height: 70%;
                        margin-top: 15%;
                        margin-left: 15%;
                        transition: 0.3s;
                    }

                    span {
                        opacity: 0;
                        font-size: smaller;
                        color: grey;
                        display: inline-block;
                        width: 140%;
                        margin-top: 5px;
                        transition: 0.3s;
                    }
                }
            }

            .users_list div:hover span {
                opacity: 1;
            }

            .welcome_by_time {
                font-size: x-large;
                font-weight: 800;
                margin-top: 25px;
                text-align: center;
            }

            .login_operation {
                position: relative;

                >div {
                    margin-top: 20px;
                    width: 100%;
                    height: 30px;
                    border: 1px solid #cdcdcd;
                    border-radius: 5px;
                    position: relative;
                }

                .user_name::before {
                    content: '';
                    position: absolute;
                    display: table;
                    width: 25px;
                    height: 25px;
                    background-size: cover;
                    background: url(@/imgs/用户名.png);
                    top: 50%;
                    transform: translateY(-60%);
                }

                .local_user_infor {
                    position: absolute;
                    top: 15px;
                    text-align: center;
                    height: 150px;
                    padding: 10px 20px;
                    overflow: scroll;
                    background-color: #fff;
                    z-index: 2;
                    border: solid 1px grey;
                    color: grey;
                    font-size: small;
                    transform: scaleY(0);
                    transition: 0.3s;
                    transform-origin: top center;

                    >div {
                        margin: 5px 0;
                    }

                    >div:hover {
                        background-color: #cdcdcd;
                        border-radius: 2px;
                    }

                }

                .user_password::before {
                    content: '';
                    position: absolute;
                    display: table;
                    width: 25px;
                    height: 25px;
                    background-size: cover !important;
                    background: url(@/imgs/锁.png);
                    top: 50%;
                    left: 4px;
                    transform: translateY(-50%);
                }

                input {
                    width: 70%;
                    height: 100%;
                    margin-left: 30px;
                    outline: none;
                    border: none;
                }

                .password_tip {
                    font-size: x-small;
                    color: red;
                    text-align: center;
                }

                .input_password_again {
                    position: absolute;

                    color: grey;
                    font-size: smaller;

                }
            }

            .remember_user {
                text-align: right;
                // color:#369bff ;
                font-size: small;
                margin: 20px 0;

                input {
                    width: 12px;
                    transform: translateY(2px);
                }
            }

            .login_btn {
                width: 100%;
                height: 35px;
                line-height: 35px;
                background-color: #369bff;
                border-radius: 15px;
                color: #fff;
                text-align: center;
                cursor: pointer
            }

            .loginBack {
                margin-top: 5px;
                cursor: pointer;
                color: grey;
                font-size: small;
            }

            .register_btn {
                margin-top: 20px
            }

            .register_user {
                display: flex;
                justify-content: center;
                width: 100%;
                height: 20px;
                margin-top: 10px;
                font-size: small;

                .go_register_btn {
                    color: #369bff;
                    cursor: pointer
                }

            }
        }

        .fail_tip {
            position: absolute;
            left: 50%;
            transform: translateX(-50%);
            width: 200px;
            height: 30px;
            line-height: 30px;
            color: #fff;
            font-weight: 600;
            border-radius: 10px;
            text-align: center;
            background-color: rgb(252, 112, 112);
        }

        .success_tip {
            position: absolute;
            left: 50%;
            transform: translateX(-50%);
            width: 200px;
            height: 30px;
            line-height: 30px;
            color: #75b050;
            font-weight: 400;
            border-radius: 10px;
            text-align: center;
            background-color: #ebf8e9;
        }

    }
}
</style>